package com.sx.gongzhong.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.MultiImageAdapter;
import com.sx.gongzhong.model.PhotoBean;
import com.sx.gongzhong.pest.AddFeedBackPest;
import com.sx.gongzhong.pest.UploadFilePest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IVoidView;
import com.sx.gongzhong.view.UploadFileView;
import com.sx.gongzhong.widget.CountEditText;
import com.sx.gongzhong.widget.LoadDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 意见反馈
 * Created by admin on 2018/1/2.
 */

public class FeedBackActivity extends BaseActivity implements UploadFileView, IVoidView {
    @BindView(R.id.et_content)
    CountEditText etContent;
    @BindView(R.id.tv_current_count)
    TextView tvCurrentCount;
    @BindView(R.id.recyclerView)
    RecyclerView rvImageRV;
    @BindView(R.id.rl_feedback_type)
    RadioGroup rlFeedbackType;
    private int max = 500;

    private MultiImageAdapter adapter;
    private List<PhotoBean> selectList = new ArrayList<>();
    private String feedbackType = "problem";

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_feedback);
        ButterKnife.bind(this);
        setTitleName("意见反馈");
        setTitleRight("提交");
        changeText(tvCurrentCount);
        etContent.setMaxNum(max);
        etContent.setOnEditTextCountLisener(new CountEditText.OnEditTextCountLisener() {
            @Override
            public void setCount(int currentCount) {
                tvCurrentCount.setText(currentCount + "/" + max);
                changeText(tvCurrentCount);
            }
        });
        rvImageRV.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        adapter = new MultiImageAdapter(this, mAddPicClickListener);
        adapter.setSelectMax(3);
        adapter.setList(selectList);
        rvImageRV.setAdapter(adapter);
        rlFeedbackType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId == R.id.type_problem){
                    feedbackType = "problem";
                }else {
                    feedbackType = "suggest";
                }
            }
        });
    }

    private void changeText(TextView tv) {
        Spannable span = new SpannableString(tv.getText());
        span.setSpan(new ForegroundColorSpan(Color.BLACK), 0, tv.getText().length() - 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(span);
    }

    @OnClick({R.id.tv_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                BaseUtil.hintKb(this);
                String content = etContent.getText().toString().trim();
                if (BaseUtil.isEmpty(content)) {
                    ToastUtils.showToast(FeedBackActivity.this, "请输入内容");
                    break;
                }
                LoadDialog.show(FeedBackActivity.this, "提交中...");
                if (selectList.size() > 0) {
                    List<File> fileList = new ArrayList<>();
                    for (PhotoBean photoBean : selectList) {
                        fileList.add(new File(photoBean.getPath()));
                    }
                    new UploadFilePest(this).uploadFile(this, fileList);
                } else {
                    addFeedBack(null);
                }
                break;
        }
    }

    private MultiImageAdapter.AddPicClickListener mAddPicClickListener = new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 3 - selectList.size();
            PictureSelector.create(FeedBackActivity.this)
                    .openGallery(PictureMimeType.ofImage())
                    .selectionMode(PictureConfig.MULTIPLE)
                    .maxSelectNum(max)// 最大图片选择数量 int
                    //.previewImage(true)// 是否可预览图片
                    .enableCrop(true).withAspectRatio(4, 3)
                    .compress(true).compressGrade(Luban.CUSTOM_GEAR)
                    .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        for (LocalMedia localMedia : picUrls) {
                            String path = localMedia.getCompressPath();
                            String type = path.substring(path.lastIndexOf("."));
                            selectList.add(new PhotoBean(path, type));
                        }
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(FeedBackActivity.this);
        ToastUtils.showToast(FeedBackActivity.this, message);
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        List<String> fileIds = new ArrayList<>();
        for (PhotoBean b : beans) {
            fileIds.add(b.getId());
        }
        addFeedBack(fileIds);
    }

    private void addFeedBack(List<String> fileIds) {
        new AddFeedBackPest(FeedBackActivity.this).addFeedBack(this, etContent.getText().toString().trim(), fileIds,feedbackType);
    }

    @Override
    public void voidView(String string) {
        LoadDialog.dismiss(FeedBackActivity.this);
        finish();
    }
}
